package cn.sh.library.gmwx.dao.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.ConnectionPoolDataSource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import virtuoso.jena.driver.VirtGraph;
import virtuoso.jena.driver.VirtModel;

import com.hp.hpl.jena.rdf.model.Model;

import cn.sh.library.gmwx.annotation.GraphDefine;
import cn.sh.library.gmwx.dao.BaseDao;

/**
 * Created by ly on 2014-10-17.
 */
public abstract class BaseDaoImpl implements BaseDao {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Resource
    private ConnectionPoolDataSource dataSource;
//    @Resource
//    private ApplicationContext applicationContext;
    private static Map<String, Model> modelCache = new HashMap<>();

    protected VirtGraph graph;

    protected Model model;

    @PostConstruct
    private void init(){
        GraphDefine graphDefine = this.getClass().getAnnotation(GraphDefine.class);
        if( graphDefine == null || StringUtils.isEmpty(graphDefine.name())){
            throw new IllegalArgumentException("missing @GraphDefine");
        }
        model = modelCache.get(graphDefine.name());
        if( model == null || model.isClosed() ) {
            model = getModel(graphDefine.name());
            modelCache.put(graphDefine.name(), model);
        }
        graph = new VirtGraph(graphDefine.name(), dataSource);

        initialization();
    }

    protected Model getModel(String name){
//        if( applicationContext.containsBean(name)){
//            return (VirtModel)applicationContext.getBean(name);
//        }
        Model model = modelCache.get(name);
        if( model == null || model.isClosed()){
            model = VirtModel.openDatabaseModel(name, dataSource);
//            Model temp_m = createModel(name);
//
//            if (temp_m != null) {
//                model.add(createModel(name));
//            }

            modelCache.put(name, model);
        }
        if( model == null ){
            throw new NullPointerException(name + "不存在");
        }
//        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext
//                .getAutowireCapableBeanFactory();
//        BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(name);
//        beanFactory.registerBeanDefinition(name, bdb.getBeanDefinition());
        return model;
    }

    protected Model createModel(String name){ return null;}

    protected void initialization(){}
}
